<?php
namespace app\task\controller;

use app\base\controller\BaseCtrl;
use think\Db;

class Base extends BaseCtrl
{
    public $beforeActionList = ['check_auth'];
    /**
     * 后台登录验证
     */
    protected function check_login()
    {
        if (!session('admin_id')) {
            if (!cookie('admin_id')) {
                return false;
            }
            session('admin_id', simple_decrypt(cookie('admin_id')));
        }
        return true;
    }
    /**
     * 后台权限验证
     */
    protected function check_auth()
    {
        if (!$this->request->isPost()) {
            if (!$this->check_login()) {
                $this->redirect('/admin/login/login');
            }
            $admin = Db::table('admin_admin')->where('id', session('admin_id'))->find();
            if (is_null($admin)) {
                session('admin_id', null);
                cookie('admin_id', null);
                $this->error('登录超时,请重新登录', '/admin/login/login');
            }
            if ($admin['disabled']) {
                session('admin_id', null);
                cookie('admin_id', null);
                $this->error('账号被禁用,请重新登录', '/admin/login/login');
            }
            if ($admin['role']) {
                $role = Db::table('admin_role')->where('id', $admin['role'])->where('disabled', 0)->find();
                if (is_null($role)) {
                    $this->error('无权访问此链接', '/admin/index/index');
                }
                if ($this->route !== '/admin/index/index' && $role['auth']) {
                    $menu = Db::table('admin_menu')->where('route', $this->route)->whereIn('id', $role['auth'])->find();
                    if (is_null($menu)) {
                        $this->error('无权访问此链接', '/admin/index/index');
                    }
                }
            }
        }
    }
}

